package com.spring.transaction;


import com.spring.annotation.Autowired;
import com.spring.bean.BeanDefinition;
import com.spring.enums.ScopeType;
import lombok.extern.slf4j.Slf4j;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * 事务管理，必须要aop 支持，否则无效
 *
 *
 * 这里 事务的传播行为 变成了   如果存在事务则合并???
 */

@Slf4j
public class TransactionManager {
	//@Autowired
	private DataSource ds;
	
	
	private static BeanDefinition bd;
	
	static {
		bd = new BeanDefinition();
		bd.setBeanName("transactionManager");
		bd.setBeanClass(TransactionManager.class);
		bd.setScope(ScopeType.SINGLE);
	}
	
	public static BeanDefinition defaultTransactionManagerDefinition() {
		return bd;
	}
	
	
	public void startTransaction() throws SQLException {
		Connection conn = TransactionSynchronizationManager.getResource();
		if (conn == null) {
			conn = ds.getConnection();
			TransactionSynchronizationManager.bindConnection(conn);
		}
		conn.setAutoCommit(false);
		log.info("开启事务");
	}
	
	public void endTransaction() throws SQLException {
		Connection conn = TransactionSynchronizationManager.getResource();
		conn.setAutoCommit(true);
		
		conn.close();
		TransactionSynchronizationManager.clear();
		log.info("关闭事务");
	}
	
	public void commit() throws SQLException {
		Connection conn = TransactionSynchronizationManager.getResource();
		conn.commit();
		log.info("提交事务");
	}
	
	public void rollback() throws SQLException {
		Connection conn = TransactionSynchronizationManager.getResource();
		conn.rollback();
		log.info("回滚事务");
	}
}
